const https = require('https');
const { Server } = require('socket.io');
const fs = require('fs');
const url = require('url');

let options = {
    key: fs.readFileSync('./ca.key'),
    ca: fs.readFileSync('./ca.csr'),
    cert: fs.readFileSync('./ca.crt')
};

const io = new Server(https);

https.createServer(options, function(req, res) {
    var pathname = url.parse(req.url).pathname;
    if(pathname == '/') {
        pathname = '/index.html'
    }
    console.log(__dirname + pathname);
    // pathname = pathname.replace(/\//g, "\\");
    fs.readFile(__dirname + pathname, function(err, data) {
        if(err) {
            if(pathname == '/favicon.ico') {
                res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8;'});
                res.end();
            }
            // console.error(err);
            res.writeHead(404, {'Content-Type': 'text/html'});
        } else {
            res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8;'});
            res.write(data.toString());
        }
        res.end();
    })
}).listen(3000, '192.168.203.72');

io.on('connection', (socket) => {
    console.log(socket);
    socket.on('message', (msg) => {
        socket.emit("message", msg)
    });
});